/**
 * 时间日期相关操作
 */

export function currentFirstDayInMonth(): Date {
  const date = new Date()
  return new Date(date.getFullYear(), date.getMonth(), 1)
}

export function currentLastDayInMonth(): Date {
  const date = new Date()
  return new Date(date.getFullYear(), date.getMonth() + 1, 0)
}

export function formatToday(fmt: string) {
  return _formatDate(new Date(), fmt)
}

export function formatDate(datetime: string | undefined | null, fmt: string): string {
  if (datetime === undefined || datetime === null || datetime === '') {
    return ''
  }
  const date = new Date(datetime)
  if (isNaN(date.getTime())) {
    return ''
  }

  return _formatDate(date, fmt)
}

function padLeftZero(str: string): string {
  return ('00' + str).substr(str.length)
}

function _formatDate(date: Date, fmt: string): string {
  if (/(y+)/.test(fmt)) {
    const yearMatch = fmt.match(/(y+)/)
    if (yearMatch) {
      fmt = fmt.replace(yearMatch[1], (date.getFullYear() + '').substr(4 - yearMatch[1].length))
    }
  }
  const WEEK = ['日', '一', '二', '三', '四', '五', '六']
  const o: { [key: string]: number | string } = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds(),
    E: WEEK[date.getDay()],
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const match = fmt.match(new RegExp(`(${k})`))
      if (match) {
        const str = o[k] + ''
        fmt = fmt.replace(match[1], match[1].length === 1 ? str : padLeftZero(str))
      }
    }
  }
  return fmt
}
